<template>
  <div :style="style">
    <template v-for="(child, index) in slotChildren" :key="index">
      <component
        :is="child"
        v-if="index === lastChildIndex"
        :style="getLastChildStyle(index)"
      />
      <component :is="child" v-else />
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed, useSlots } from 'vue'
import gapSizes from './gapSizes'

const props = defineProps({
  width: {
    type: String,
    default: 'auto',
  },
  gap: {
    type: String,
    default: 'small',
  },
  lastItemPos: {
    type: String,
    default: null,
  },
  alignItems: {
    type: String,
    default: 'center',
  },
})

const slots = useSlots()
const slotChildren = computed(() => {
  return slots.default?.() || []
})

const style = computed(() => {
  return {
    width: props.width,
    display: 'flex',
    alignItems: props.alignItems,
    gap: `${gapSizes[props.gap]}px`,
    flexWrap: 'wrap',
    position: 'relative',
  }
})

const lastChildIndex = computed(() => slotChildren.value.length - 1)

const getLastChildStyle = (index: number) => {
  if (index === lastChildIndex.value) {
    const lastChildStyle = { ...(slotChildren.value[index].props?.style || {}) }
    if (props.lastItemPos === 'fill') {
      lastChildStyle.flex = 1
    } else if (props.lastItemPos === 'aside') {
      lastChildStyle.marginLeft = 'auto'
    }
    return lastChildStyle
  }
  return {}
}
</script>
